package cn.edu.nju.software.action.book;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.BookShow;
import cn.edu.nju.software.bean.show.CategoryShow;
import cn.edu.nju.software.bean.storage.Book;
import cn.edu.nju.software.service.intf.BookService;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class GetHotBooksAction extends ActionSupport implements SessionAware {

	private BookService bookService;
	private Map<String, Object> session;

	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public String execute() throws Exception {
		if (session.get(Constants.SESSION_HOT) == null) {
			List<Book> hotBooks = bookService.getHotBooks();
			Map<Integer, BookShow> hotBooksMap = new LinkedHashMap<Integer, BookShow>(hotBooks.size());
			@SuppressWarnings("unchecked")
			Map<Integer, CategoryShow> categoriesMap = (Map<Integer, CategoryShow>) session.get(Constants.SESSION_ALL_CATEGORIES);
			for(Book book : hotBooks) {
				hotBooksMap.put(book.getBookID(), new BookShow(book, categoriesMap.get(book.getCategoryID())));
			}
			hotBooks = null;
			session.put(Constants.SESSION_HOT, hotBooksMap);
		}
		return SUCCESS;
	}
}
